<template>
  <span @click="openSelector">
    <slot></slot>
  </span>
  <view class="component-container" v-if="isVisible">
    <view
      class="top-row"
      :style="{ height: completeSafeHeight + 'px', paddingTop: safeAreaTop + 'px' }"
      v-if="isCustomPageTop"
    >
      <span @click="closeComponentView">
        <image src="./icon/close.svg" class="close" />
      </span>
      <span class="title">国家地区</span>
    </view>
    <view class="search">
      <view class="search-input">
        <image src="./icon/search.svg" class="icon" />
        <input placeholder="搜索" class="input" confirm-type="search" @confirm="search($event)" />
      </view>
    </view>
    <view class="list-selector">
      <view class="list">
        <scroll-view
          :scroll-y="true"
          :show-scrollbar="false"
          :scroll-into-view="tid"
          :scroll-with-animation="true"
          class="list-scroll-view"
          @scroll="onScroll"
        >
          <template v-for="charKey in Object.keys(listsForFirstChar)" :key="charKey">
            <h2 :id="charKey" class="charKey" v-show="!searchMode.isActive">{{ charKey }}</h2>
            <view
              class="item"
              v-for="item in listsForFirstChar[charKey]"
              :key="item.name"
              v-show="item.name.includes(searchMode.keyword)"
              @click="select(item.tel)"
              >{{ item.name }}(+{{ item.tel }})</view
            >
          </template>
        </scroll-view>
      </view>

      <view class="first-char-nav">
        <span
          v-show="!searchMode.isActive"
          :class="{ active: currentCharKey === char }"
          v-for="char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"
          :key="'char-nav-' + char"
          @click="moveTo(char)"
          class="char"
          >{{ char }}</span
        >
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import $store from '@/store'
import { ref, nextTick, getCurrentInstance, onMounted, watch } from 'vue'
import { getCurrentPageConfig } from './utils'
const { safeAreaTop, completeSafeHeight } = $store.app.getSystemParam()
const isCustomPageTop = ref(false)
// const rawPageTitle = ref('')
// 初始化isCustomPageTop 与 rawPageTitle
getCurrentPageConfig().then((pageConfig) => {
  isCustomPageTop.value = pageConfig?.style?.navigationStyle === 'custom'
  // rawPageTitle.value = pageConfig?.style?.navigationBarTitleText ?? ''
})
const props = defineProps({
  modelValue: {
    type: String,
    require: true
  }
})
const emits = defineEmits<{
  (e: 'update:modelValue', newVal: string): void
}>()
const isVisible = ref<boolean>(false)
interface ListItem {
  short: string
  name: string
  en: string
  tel: string
}
const listData = ref<ListItem[]>([]) // 总列表数据
const listsForFirstChar = ref<{ [key: string]: ListItem[] }>({}) // "A":[{},{},...]
const searchMode = ref({
  keyword: '',
  isActive: false
})
// 各charKey 标题的位置
const charKeyTitlePosition = ref<{ [key: string]: number }>({})
// 判断当前位置所处的位置
const currentCharKey = ref<string>()
function onScroll(event: any) {
  for (let key in charKeyTitlePosition.value) {
    const charScrollTop = charKeyTitlePosition.value[key]
    const currentScrollTop = event.detail.scrollTop
    if (charScrollTop >= currentScrollTop) {
      currentCharKey.value = key
      return
    }
  }
  console.log('当前是：', currentCharKey.value)
}
function search(event: any) {
  const keyword = event.target.value
  searchMode.value.keyword = keyword
  searchMode.value.isActive = keyword !== ''
}
// 选择了
function select(tel: string) {
  emits('update:modelValue', tel)
  isVisible.value = false
}

// 锚点定位
const tid = ref('')
function moveTo(charKey: string) {
  nextTick(() => {
    console.log('to', charKey)
    tid.value = charKey
  })
}
const instance = getCurrentInstance()
// 对对象的key进行排序，返回新的
function sortObjectKey(listsForFirstChar: { [key: string]: ListItem[] }) {
  // 获取对象的键，并按字母顺序排序
  const sortedKeys = Object.keys(listsForFirstChar).sort()
  // 创建一个新的对象，按排序后的键存储相应的列表项
  const sortedListsForFirstChar = sortedKeys.reduce(
    (acc, key) => {
      acc[key] = listsForFirstChar[key]
      return acc
    },
    {} as { [key: string]: ListItem[] }
  )
  return sortedListsForFirstChar
}

function openSelector() {
  // 如果没有自定义标题需要修改标题
  // if (!isCustomPageTop.value) {
  //   uni.setNavigationBarTitle({
  //     title: '地区选择'
  //   })
  // }
  isVisible.value = true
  if (listData.value.length == 0)
    import('./list.json').then(({ list }) => {
      listData.value = list
      for (let item of list) {
        const c = item.en[0]
        let listForChar = listsForFirstChar.value[c]
        if (listForChar == null) listForChar = listsForFirstChar.value[c] = []
        listForChar.push(item)
      }
      // 对key进行排序
      listsForFirstChar.value = sortObjectKey(listsForFirstChar.value)
      // 完成dom的渲染后获取各charKey的scrollTop
      nextTick(() => {
        // 没有这个，得到都会为null，表示在下面dom渲染完成后调用
        let query = uni.createSelectorQuery().in(instance)
        const keys = Object.keys(listsForFirstChar.value)
        for (const [index, key] of keys.entries()) {
          // 设置位置（刚进来肯定是第一个）
          if (index === 0) currentCharKey.value = key
          query
            .select(`#${key}`)
            .fields({ rect: true }, (res: any) => (charKeyTitlePosition.value[key] = res.top))
            .exec()
        }
      })
    })
}
// 关闭选择器
function closeComponentView() {
  // if (!isCustomPageTop.value) {
  //   uni.setNavigationBarTitle({
  //     title: rawPageTitle.value
  //   })
  // }
  isVisible.value = false
}
</script>

<style scoped lang="scss">
.component-container {
  position: fixed;
  z-index: 1000;
  display: flex;
  background-color: #fff;
  inset: 0;
  flex-direction: column;

  .top-row {
    position: relative;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    box-sizing: border-box;

    .close {
      width: 35rpx;
      height: 35rpx;
    }

    .title {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  .search {
    $search-padding-size: 25rpx;

    padding: $search-padding-size * 0.5 $search-padding-size;
    width: 100%;
    box-sizing: border-box;

    $search-input-height: 80rpx;

    .search-input {
      display: flex;
      align-items: center;
      padding: 0 $search-input-height * 0.5;
      box-sizing: border-box;
      height: $search-input-height;
      border-radius: $search-input-height * 0.5;
      background-color: #f5f5f5;

      .icon {
        width: 30rpx;
        height: 30rpx;
      }

      .input {
        margin-left: 20rpx;
        flex-grow: 1;
      }
    }
  }

  .list-selector {
    position: relative;
    display: flex;
    overflow: auto;
    height: 0;
    background-color: #fff;
    flex-grow: 1;

    $first-char-nav-width: 40rpx;

    .list {
      position: absolute;
      display: flex;
      overflow: auto;
      padding: 0 25rpx;
      inset: 0 $first-char-nav-width 0 0;
      box-sizing: border-box;
      flex-direction: column;

      /** scroll-view取消滚动条 */
      .list-scroll-view ::-webkit-scrollbar {
        display: none;
      }

      .list-scroll-view {
        flex-grow: 1;
        height: 0;
        font-size: 30rpx !important;
        %basic-font-style {
          height: 100rpx;
          color: black;
          line-height: 100rpx;
        }

        .charKey {
          @extend %basic-font-style;

          font-weight: 700;
        }

        .item {
          @extend %basic-font-style;
        }
      }
    }

    .first-char-nav {
      position: absolute;
      right: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      width: $first-char-nav-width;
      height: 100%;
      flex-direction: column;
      font-size: 25rpx;

      $font-size: $first-char-nav-width * 0.8;

      .char {
        width: $font-size;
        height: $font-size;
        border-radius: 50%;
        line-height: $font-size;
        text-align: center;
      }

      .active {
        color: #fff;
        background-color: #fedc04;
      }
    }
  }
}
</style>
